package com.dish.action;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dish.bean.MyUsers;
import com.dish.dao.UserDAO;
import com.dish.dao.UserDAOImpl;
import com.dish.utils.JDBCUtils;

/**
 * Servlet implementation class ShowUsers
 */
@WebServlet("/ShowUsers")
public class ShowUsers extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowUsers() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ArrayList<MyUsers> lst;
		try {
			lst = getData();
			request.setAttribute("lst", lst);
			request.getRequestDispatcher("userlist.jsp").forward(request, response);
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
	}
	private ArrayList<MyUsers> getData() throws SQLException
	{
		ArrayList<MyUsers> lst = new ArrayList<MyUsers>();
		Connection conn = null;
		PreparedStatement ps =null;
		ResultSet rs = null;
		try {
			conn = JDBCUtils.getConnection();
			ps = conn.prepareStatement("select * from users");
			rs = ps.executeQuery();
			while(rs != null && rs.next()) {
				MyUsers usr = new MyUsers();
				usr.setUserid(rs.getInt("userid"));
				usr.setUsername(rs.getString("username"));
				usr.setPhonenumber(rs.getString("phonenumber"));
				usr.setCreatedate(rs.getTimestamp("createdate"));
				if(rs.getString("isadmin").equals("YES")) {
					usr.setIsadmin("是");
				}
				else {
					usr.setIsadmin("否");
				}
				
				lst.add(usr);
			}
			return lst;
		}catch(RuntimeException e) {
			e.printStackTrace();
			return null;
		}finally {
			JDBCUtils.free(rs, ps, conn);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
